package com.risen.test.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 文件上传到服务器
 *
 * @auther lmj
 * @date 2019/8/16
 */

@RestController
@RequestMapping("/test")
public class SimpleUpload {
    // 文件上传的路径
    private String uploadPath = "E:\\img\\";
    // 文件访问的路径
    private String url = "E:\\img\\";

    // 单文件上传
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Map<String, String> upload(@RequestParam("file") MultipartFile file) {

        Map<String, String> map = new HashMap<>();
        if (!file.isEmpty()) {
            // 创建文件对象
            File files = new File(uploadPath + file.getOriginalFilename());
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(files));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
                map.put("400", "文件上传失败");
                return map;
            }
            map.put("success", url + files.getName());
            return map;
        } else {
            map.put("201", "文件上传失败,文件为空");
            return map;
        }
    }


    // 多文件上传
    @ResponseBody
    @RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
    public Map<String, String> batchUpload(@RequestParam("files") MultipartFile[] files) {


        Map<String, String> map = new HashMap<>();
        String uploadedFileName = Arrays.stream(files).map(x -> x.getOriginalFilename())
                .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
        if (StringUtils.isEmpty(uploadedFileName)) {
            map.put("201", "文件上传失败,文件为空");
            return map;
        }
        List<String> path = new ArrayList<String>();
        try {
            path = saveUploadedFiles(Arrays.asList(files));
        } catch (IOException e) {
            map.put("400", "文件上传失败");
            return map;
        }
        map.put("success", path.toString());
        return map;
    }
    
    private List<String> saveUploadedFiles(List<MultipartFile> files) throws IOException {
        List<String> paths = new ArrayList<>();
        String urls = SimpleUpload.class.getResource("/").getPath();
        String url = urls + "img/";
        File fileImg = new File(url);
        url.substring(1);
        if (!fileImg.exists()) {
            fileImg.mkdir();
        }
        System.out.println(urls);
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }
            byte[] bytes = file.getBytes();
            Path path = Paths.get(url + file.getOriginalFilename());
            paths.add(url + file.getOriginalFilename());            //保存上传文件的访问路径
            Files.write(path, bytes);
        }
        return paths;
    }
}
